<template>
  <div class="details">

    <van-swipe :loop="true" :autoplay="3000">
      <van-swipe-item v-for="page in detail.photo" :key="page.id">
        <img :src="page.url" class="swipe-image" />
      </van-swipe-item>
    </van-swipe>

  <div :style="{padding: '6px'}">
      <!-- 标题 -->
      <h3>{{ detail.title }}</h3>
      <!-- 描述 -->
      <div>
        <span :style="{color: 'red', fontWeight: 700}">￥{{ detail.price }}</span>
        <span :style="{paddingLeft: '12px', textDecoration: 'line-through'}">{{ detail.originPrice }}</span>
      </div>
    </div>

    <van-divider>图文详情</van-divider>

    <van-image
      lazy-load
      v-for="img in detail.descContentList"
      :key="img.photo.id"
      :src="img.photo.url"
      :style="{display: 'block'}"
    />

    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" dot />
      <van-goods-action-icon icon="cart-o" text="购物车" badge="5" @click="$router.push('/cart')" />
      <van-goods-action-icon icon="shop-o" text="店铺" badge="12" />
      <van-goods-action-button type="warning" text="加入购物车" @click="handleAddToCart" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
    <div class="back"  @click="$router.back()">
      <van-icon name="arrow-left" />
      </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { getDetails } from '@/api/details'
export default {
  name: 'Details',
  data () {
    return {
      detail: null
    }
  },
  async created () {
    console.log(this.$route)
    const result = await getDetails(this.$route.params.id)
    console.log(result)
    this.detail = result.detail
  },
  methods: {
    ...mapMutations(['addTocart']), // mutation中 只有一个函数可以直接用 $store 多个用mapMutations
    // ...mapMutations(['addTocart'])相当于addTocart(payload) {} 函数声明
    handleAddToCart () {
      const { id, image, title, price } = this.detail
      // 当前需要添加到购物车的商品对象
      const currentgoods = {
        id,
        image,
        title,
        price,
        num: 1
      }
      // 将当前的商品 保存 到 store 中的 state的 cart数组中，调用mutation 中的方法 需要用store的comit提交到
      console.log(currentgoods)
      // console.log(store)
      // this.$store.commit('addTocart', currentgoods)
      this.addTocart(currentgoods)
    }
  }
}
</script>

<style lang="less" scoped>
.details{
  height: 100%;
  overflow-x:hidden;
  position: relative;
}
.swipe-image {
  width: 100%;
  height: 100%;
}
.back{
  width: 35px;
  height: 35px;
  line-height: 35px;
  color: white;
  text-align: center;
  background: rgba(0,0,0,0.3);
  border-radius:50%;
  position: absolute;
  top: 5px;
  left: 5px;
}
</style>
